package com.ruoyi.statisticalCenter.controller;

import cn.hutool.core.net.URLEncoder;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.domain.vo.TableVo;
import com.ruoyi.common.service.TableService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.cache.CustomCacheFilter;
import com.ruoyi.hqfinance.domain.HqNetworkBillDetail;
import com.ruoyi.logistic.domain.PageDate;
import com.ruoyi.logistic.domain.PageInfo;
import com.ruoyi.logistic.utils.TableUtils;
import com.ruoyi.statisticalCenter.domain.ScEnterPaiGrossProfitSheet;
import com.ruoyi.statisticalCenter.domain.ScOutPortWarehouseGrossProfitSheet;
import com.ruoyi.statisticalCenter.domain.ScOutboundEliminate;
import com.ruoyi.statisticalCenter.domain.ScWeightFlowDirectionMonitoring;
import com.ruoyi.statisticalCenter.domain.vo.*;
import com.ruoyi.statisticalCenter.service.ScEnterPaiGrossProfitSheetService;
import com.ruoyi.statisticalCenter.service.ScOutPortWarehouseGrossProfitSheetService;
import com.ruoyi.statisticalCenter.service.ScOutboundEliminateService;
import com.ruoyi.statisticalCenter.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping("/sc/outPortWarehouseGrossProfitSheet")
@Api(tags = "统计中心-出港包仓毛利报表")
public class ScOutPortWarehouseGrossProfitSheetController {
    @Autowired
    private ScOutPortWarehouseGrossProfitSheetService scOutPortWarehouseGrossProfitSheetService;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private TableService tableService;
    @Autowired
    private RedisUtil redisUtil;

    //@CustomCacheFilter
    @ApiOperation("汇总")
    @PostMapping("/collect")
    public R collect(@RequestBody ScOutPortWarehouseGrossProfitSheetVo vo) {
        if (vo != null) {
            String startTime = vo.getStartTime().replace("-", "");
            String endTime = vo.getEndTime().replace("-", "");
            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
            vo.setUpdateStartTime(addOneDayToDateString(vo.getStartTime()));
            vo.setUpdateEndTime(addOneDayToDateString(vo.getEndTime()));
        }
        String list = scOutPortWarehouseGrossProfitSheetService.selectDisposition().toString();

// 构建Redis键
        String redisKey = "sc_out_port_warehouse_gross_profit_sheet:collect:" + vo.getStartTime() + ":" + vo.getEndTime()
                + ":" + vo.getNetworkLevel() + list + vo.getPageDate().getPageNum() + vo.getPageDate().getPageSize();
        // 检查Redis中是否存在数据
       /* R redisResult = redisUtil.getObject(redisKey, R.class);
        if (redisResult != null) {
            return redisResult; // 如果Redis中存在数据，则直接返回
        }*/
        // 如果Redis中不存在数据，则从数据库中查询

        R databaseResult = scOutPortWarehouseGrossProfitSheetService.collectCache(vo);
        if (databaseResult.getData() == null){
            databaseResult = scOutPortWarehouseGrossProfitSheetService.collectNew(vo);
        }
//        R databaseResult = scOutPortWarehouseGrossProfitSheetService.collectNew(vo);

        // 将数据库查询结果存储到Redis，并设置过期时间为一天
        redisUtil.setObject(redisKey, databaseResult, 600);
        return databaseResult;
    }

    @ApiOperation("导出")
    @PostMapping("/export")
    @ResponseBody
    public void export(@RequestBody ScOutPortWarehouseGrossProfitSheetVo vo) {
        
        if (vo != null) {
            String startTime = vo.getStartTime().replace("-", "");
            String endTime = vo.getEndTime().replace("-", "");
            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
            PageDate pageDate = new PageDate();
            pageDate.setPageNum(1);
            pageDate.setPageSize(10000);
            vo.setPageDate(pageDate);
            
            vo.setUpdateStartTime(addOneDayToDateString(vo.getStartTime()));
            vo.setUpdateEndTime(addOneDayToDateString(vo.getEndTime()));
        }
        String fileName = "attachment;filename=" + URLEncoder.createDefault().encode("出港包仓毛利报表", Charset.forName("utf-8")) + ".xls";
        response.setHeader("Content-Disposition", fileName);
//        List<ScOutPortWarehouseGrossProfitSheet> list = scOutPortWarehouseGrossProfitSheetService.collectList(vo);
//        ExcelUtil<ScOutPortWarehouseGrossProfitSheet> util = new ExcelUtil(ScOutPortWarehouseGrossProfitSheet.class);
//        util.exportExcel(response, list, "出港包仓毛利报表");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        scOutPortWarehouseGrossProfitSheetService.collectList(vo, outputStream);
    }

    @ApiOperation("cache")
    @PostMapping("cache")
    public R cache(@RequestBody DateStrVo time) {
        return scOutPortWarehouseGrossProfitSheetService.cache(time);
    }

    @PostMapping("/updateDisposition")
    @ApiOperation("修改配置参数")
    public R updateDisposition(@RequestBody ScOutPortWareDispositionVo vo) {
        return scOutPortWarehouseGrossProfitSheetService.updateDisposition(vo);
    }

    @GetMapping("/selectDisposition")
    @ApiOperation("查询配置参数")
    public R<ScOutPortWareDispositionCloentVo> selectDisposition() {
        return scOutPortWarehouseGrossProfitSheetService.selectDisposition();
    }


    @ApiOperation("点击跳转")
    @PostMapping("/point")
    public R point(@RequestBody ScOutPortWarehouseGrossProfitSheetPointVo vo) {
        if (vo != null) {
            String startTime = vo.getStartTime().replace("-", "");
            String endTime = vo.getEndTime().replace("-", "");
            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
        }
        List<HqNetworkBillDetail> list = scOutPortWarehouseGrossProfitSheetService.point(vo);
        List<TableVo> fieldList = tableService.getFieldAnnotation(new HqNetworkBillDetail());
        return TableUtils.handleListResponse(list, fieldList, "暂无数据");
    }

//    /**
//     * 下载模板
//     */
//    @ApiOperation("下载模板")
//    @GetMapping("/importTemplate")
//    @ResponseBody
//    public AjaxResult importTemplate()
//    {
//        ExcelUtil<ScOutboundEliminate> util = new ExcelUtil<ScOutboundEliminate>(ScOutboundEliminate.class);
//        return util.importTemplateExcel("剔除票数模板");
//    }

//    @ApiOperation("汇总2")
//    @PostMapping("/collect2")
//    public R collectNew(@RequestBody ScOutPortWarehouseGrossProfitSheetVo vo) {
//        if (vo != null) {
//            String startTime = vo.getStartTime().replace("-", "");
//            String endTime = vo.getEndTime().replace("-", "");
//            vo.setStartTime(startTime);
//            vo.setEndTime(endTime);
//            vo.setUpdateStartTime(addOneDayToDateString(vo.getStartTime()));
//            vo.setUpdateEndTime(addOneDayToDateString(vo.getEndTime()));
//        }
//        return R.ok(PageInfo.info(scOutPortWarehouseGrossProfitSheetService.collectNew(vo)));
//    }


    //日期加一天
    private String addOneDayToDateString(String startDate) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

        // 解析输入的字符串为LocalDate对象
        LocalDate date = LocalDate.parse(startDate, formatter);

        // 将日期加一天
        LocalDate newDate = date.plusDays(1);

        // 将新的日期转换回字符串
        return newDate.format(formatter);
    }


}
